package org.restorator.dao.implement;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.restorator.dao.base.TableDao;
import org.restorator.dao.implement.engin.TableEnricher;
import org.restorator.dao.implement.engin.TableRowMapper;
import org.restorator.dao.jdbc.AbstractJdbsTemplate;
import org.restorator.dao.jdbc.Enricher;
import org.restorator.dao.jdbc.PreparedSetter;
import org.restorator.dao.jdbc.SimpleResultSetExtractor;
import org.restorator.entity.Table;
import org.restorator.exception.DataStoreException;

public class TableDaoImpl extends AbstractJdbsTemplate<Table, Integer>
		implements TableDao {

	private static final String SQL_SELECT_ALL = "SELECT TABLE_ID, TABLE_X, TABLE_Y,"
			+ " t.Status_NAME FROM  PLACE p, TABLE_STATUS t WHERE p.STATUS_ID = t.STATUS_ID";
	private static final String SQL_SELECT_BY_TABLE_ID = "SELECT TABLE_ID, TABLE_X, TABLE_Y, "
			+ "t.Status_NAME FROM  PLACE p, TABLE_STATUS t WHERE p.Table_ID = ? AND p.STATUS_ID = t.STATUS_ID";

	
	private static final String SQL_DELETE_TABLE = "DELETE FROM PLACE WHERE TABLE_ID = ?";

	public TableDaoImpl() {
	}

	@Override
	public Table get(final Integer id) throws DataStoreException {
		return executeParameter(SQL_SELECT_BY_TABLE_ID,
				new SimpleResultSetExtractor(new TableRowMapper()),
				new TableEnricher(new OrderDaoImpl()), 
                                new PreparedSetter() {
					@Override
					public void setParameters(PreparedStatement ps)
							throws SQLException {
						ps.setInt(1, id);
					}
				});
	}

	@Override
	public Table update(Table persistElement) throws DataStoreException {
		return null;
	}

	@Override
	public void delete(final Table deleted) throws DataStoreException {
            //deleting Orders with foreign key

//        todo:Check!
            if(deleted.getOrder()!=null){
                OrderDaoImpl odi = new OrderDaoImpl();
                odi.delete(deleted.getOrder());            
            }
            //deleting Table
            updateOne1(SQL_DELETE_TABLE,
                deleted,
                Enricher.NULL,
                new PreparedSetter() {
                    @Override
                    public void setParameters(PreparedStatement ps) throws SQLException {
                        ps.setInt(1, deleted.getTableID());
                    }
                });
	}

	@Override
	public long count() {
		return 0;
	}

	@Override
	public Integer save(Table persist, Object... addParams)
			throws DataStoreException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Table> getAll() throws DataStoreException {
		return list(SQL_SELECT_ALL, new SimpleResultSetExtractor(
				new TableRowMapper()), new TableEnricher(new OrderDaoImpl()));

	}

	@Override
	public boolean exist(Integer id) {
		// TODO Auto-generated method stub
		return false;
	}

}
